import {Button, Space, Table, Tag, Popconfirm, Form, Input, Select, Col, Row, Modal, FormProps} from "antd";
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useEffect, useState } from 'react';
import {getBlogList, deleteBlog} from "@/request/blog"
import type { GetProp, TableProps } from 'antd';


const BlogList = () => {
    const [form] = Form.useForm();
    type ColumnsType<T> = TableProps<T>['columns'];
    type TablePaginationConfig = Exclude<GetProp<TableProps, 'pagination'>, boolean>;
    interface DataType {
        id: string;
        authorAvatar: string;
        authorId: string;
        authorName: string;
        commentCount: number;
        content: string;
        description: string;
        img: string;
        praise: number;
        readCount: number;
        time: string;
        title: string;
    }
    interface TableParams {
        pagination?: TablePaginationConfig;
        sortField?: string;
        sortOrder?: string;
        filters?: Parameters<GetProp<TableProps, 'onChange'>>[1];
    }
    const columns: ColumnsType<DataType>['columns'] = [
        {
            title: 'id',
            dataIndex: 'id',
            sorter: (a, b) => a.id - b.id,
            render: (id) => `${id}`,
        },
        {
            title: '作者',
            dataIndex: 'authorName',
        },
        {
            title: '标题',
            dataIndex: 'title',
        },
        {
            title: '评论数',
            dataIndex: 'commentCount',
            key: 'commentCount',
            sorter: (a, b) => a.commentCount - b.commentCount,
            render: (commentCount) => (
                <Tag color="red">{commentCount}</Tag>
            ),
        },
        {
            title: '阅读数',
            dataIndex: 'readCount',
            key: 'readCount',
            sorter: (a, b) => a.readCount - b.readCount,
            render: (readCount) => (
                <Tag color="green">{readCount}</Tag>
            ),
        },
        {
            title: '点赞数',
            dataIndex: 'praise',
            key: 'praise',
            sorter: (a, b) => a.praise - b.praise,
            render: (praise) => (
                <Tag color="blue">{praise}</Tag>
            ),
        },
        {
            title: '时间',
            dataIndex: 'time',
        },
        {
            title: 'Action',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={showModal}>编辑</a>
                    <Popconfirm
                        title="删除"
                        description="确认删除该条博客？"
                        cancelText={'取消'}
                        okText={'确认'}
                        onConfirm={() => handleDeleteItem(record.id) }
                        icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                    >
                        <a>删除</a>
                    </Popconfirm>
                </Space>
            ),
        },
    ]
    const [data, setData] = useState<DataType[]>();
    const [loading, setLoading] = useState(false);
    const [tableParams, setTableParams] = useState<TableParams>({
        pagination: {
            current: 1,
            pageSize: 10,
        },
    });

    const [query, setQuery] = useState(
        {
            pageSize: tableParams.pagination?.pageSize,
            pageNum: tableParams.pagination?.current,
            authorId: '',
            title: '',
            order: '',  // 排序方式
        }
    )

    // 处理输入框值改变的事件
    const handleInputChange = (name, event) => {
        setQuery({
            ...query, // 保持其他搜索条件不变
            [name]: event.target.value, // 更新指定搜索条件的值
        });
    };

    // 重置搜索条件
    const handleReset = () => {
        setQuery({
            authorId: "",
            order: "",
            pageNum: 1,
            pageSize: 10,
            title: ''
        });
        fetchData()
    };

    // 获取数据
    const fetchData = async () => {
        setLoading(true);
        const res: GetBlogAPIRes = await getBlogList(query as GetBlogAPIReq)
        if (res.code == 200) {
            setData(res.data.records);
            setLoading(false);
            setTableParams({
                ...tableParams,
                pagination: {
                    ...tableParams.pagination,
                    total: res.data.total,
                },
            });
        }
    };

    const handleDeleteItem = (async (id: string) => {
        const res = await deleteBlog(id);
        if (res.code === 200) {
            fetchData();
        }
    });

    /*
    * 这句代码在 useEffect 钩子中使用 fetchData 函数来获取数据，并在 tableParams 变化时重新调用 fetchData。具体来说，useEffect 会在以下情况下执行：
      组件挂载时（即组件首次渲染时）。
      依赖数组中的值发生变化时。
    * */
    useEffect(() => {
         fetchData();
    }, []);

    const handleTableChange: TableProps['onChange'] = (pagination, filters, sorter) => {
        setTableParams({
            pagination,
            filters,
            ...sorter,
        });
        if (pagination.pageSize !== tableParams.pagination?.pageSize) {
            setData([]);
        }
    };

    const layout = {
        // labelCol: { span: 8 },
        // wrapperCol: { span: 16 },
    };

    const onFinish = (values: any) => {
        // console.log(values);
    };

    const onReset = () => {
        form.resetFields();
    };

    const onFill = () => {
        form.setFieldsValue({ note: 'Hello world!', gender: 'male' });
    };

    // const handleInputChange = (event) => {
    //     query.title = event.target.value;
    // }

    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [modalText, setModalText] = useState('Content of the modal');

    const showModal = () => {
        setOpen(true);
    };

    const handleOk = () => {
        setModalText('The modal will be closed after two seconds');
        setConfirmLoading(true);
        setTimeout(() => {
            setOpen(false);
            setConfirmLoading(false);
        }, 2000);
    };

    const handleCancel = () => {
        console.log('Clicked cancel button');
        setOpen(false);
    };

    type FieldType = {
        username?: string;
        password?: string;
        remember?: string;
    };

    const onFinishForm: FormProps<FieldType>['onFinish'] = (values) => {
        console.log('Success:', values);
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    return(
        <div>
            <Form
                {...layout}
                form={form}
                name="control-hooks"
                onFinish={onFinish}
            >
                <Row gutter={16}>
                    <Col span={6}>
                        <Form.Item name="title" label="标题" rules={[{ required: true }]}>
                            <Input
                                type="text"
                                placeholder="关键词"
                                value={query.title}
                                onChange={(event) => handleInputChange('title', event)}
                            />
                        </Form.Item>
                    </Col>
                    {/*<Col span={6}>*/}
                    {/*    <Form.Item name="note" label="Note" rules={[{ required: true }]}>*/}
                    {/*        <Input />*/}
                    {/*    </Form.Item>*/}
                    {/*</Col>*/}
                    {/*<Col span={6}>*/}
                    {/*    <Form.Item name="note" label="Note" rules={[{ required: true }]}>*/}
                    {/*        <Input />*/}
                    {/*    </Form.Item>*/}
                    {/*</Col>*/}
                    <Col span={6} style={{display: "flex", justifyContent: "center"}}>
                        <Button type="primary" htmlType="submit" style={{marginRight: "10px"}} onClick={fetchData}>搜索</Button>
                        <Button type="primary" htmlType="submit" onClick={handleReset}>重置</Button>
                    </Col>
                </Row>
            </Form>
            <Table
                columns={columns}
                rowKey={(record) => record.id}
                dataSource={data}
                pagination={tableParams.pagination}
                loading={loading}
                onChange={handleTableChange}
            />
            <Modal
                title="编辑"
                open={open}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
                width={800}
            >
                <Form
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinishForm}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Row>
                        <Col span={12}>
                            <Form.Item<FieldType>
                                label="Username"
                                name="username"
                                rules={[{ required: true, message: 'Please input your username!' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item<FieldType>
                                label="Password"
                                name="password"
                                rules={[{ required: true, message: 'Please input your password!' }]}
                            >
                                <Input.Password />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </div>
    )
}
export default BlogList